import Vue from 'vue'
import axios from 'axios'
import qs from 'qs'

/**
 * axios 版本
 */
export function request (params) {
  // axios post的data必须转换为URLSearchParams后台才能接收到
  // var host = 'http://wx.ufunet.cn/'
  let host = ''
  return new Promise((resolve, reject) => {
    axios({
      method: params.method ? params.method : 'get',
      url: host + params.url,
      data: (params.method !== 'post') ? {} : qs.stringify(params.data),
      params: (params.method === 'post') ? {} : params.data,
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'Content-type': 'application/x-www-form-urlencoded;charset=utf-8'
        // 跨域相关参数
        // 'Access-Control-Allow-Origin':'*',
        // 'Access-Control-Allow-Methods':'POST,GET,OPTIONS',
        // 'Access-Control-Allow-Headers':'Content-Type,Authorization'
      }
    }).then(response => {
      if (response.status === 200) {
        // console.log(params.url + '>>>>>', JSON.stringify(response.data))
        resolve(response.data)
      } else {
        console.log(response.status)
      }
    }).catch((error) => {
      if (reject) {
        reject(error)
      } else {
        console.log('common error func')
      }
    })
  })
}

Vue.use({
  install: () => {
    Vue.prototype.$http = request
  }
})
